package cn.wolfcode.wolf2w.resolve;

import cn.wolfcode.wolf2w.annotation.UserInfoParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserInfoResolve implements HandlerMethodArgumentResolver {

	@Autowired
	private IUserInfoRedisService userInfoRedisService;

	/**
	 * 用户参数解析器
	 * 将请求映射方法形式参数声明的UserInfo类型参数解析成当前登录用户对象并注入
	 */
	@Override
	public boolean supportsParameter(MethodParameter methodParameter) {
		return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserInfoParam.class);
	}

	@Override
	public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
		HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
		String token = request.getHeader("token");
		UserInfo user = userInfoRedisService.getUserByToken(token);
		return user;
	}
}
